package com.hadwinling.controller;

import com.alibaba.fastjson.JSON;
import com.hadwinling.utils.FileUtils;
import com.hadwinling.utils.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class indexController {
    @GetMapping("/")
    public String index() {
        return "training-set";
    }

    @PostMapping("/add")
    @ResponseBody
    public Result imageUpload(@RequestParam("imgFile") MultipartFile file) {
        Result result = new Result();

        String result_msg;
        int code;

        if (file.getSize() / 1000 > 100) {
            code = 110;
            result_msg = "图片大小不能超过100KB";
            result.setCode(code);
            result.setMsg(result_msg);
        } else {
            //判断上传文件格式
            String fileType = file.getContentType();
            if (fileType.equals("audio/mpeg")) {
                // 要上传的目标文件存放的绝对路径
                //用src为保存绝对路径不能改名只能用原名，不用原名会导致ajax上传图片后在前端显示时出现404错误-->原因未知
//                String localPath="F:\\IDEAProject\\imageupload\\src\\main\\resources\\static\\img";
                final String localPath = "E:\\Workspace\\IdeaWorkSpace\\zz\\src\\main\\resources\\static\\img";
                //上传后保存的文件名(需要防止图片重名导致的文件覆盖)
                //获取文件名
                String fileName = file.getOriginalFilename();
                //获取文件后缀名
                String suffixName = fileName.substring(fileName.lastIndexOf("."));
                //重新生成文件名
                fileName = UUID.randomUUID() + suffixName;
                if (FileUtils.upload(file, localPath, fileName)) {
                    //文件存放的相对路径(一般存放在数据库用于img标签的src)
                    String relativePath = "img/" + fileName;
                    //前端根据是否存在该字段来判断上传是否成功
                    result_msg = "图片上传成功";
                    code = 200;
                    result.setCode(code);
                    result.setMsg(result_msg);
                } else {
                    result_msg = "图片上传失败";
                    code = 100;
                    result.setCode(code);
                    result.setMsg(result_msg);
                }
            } else {
                result_msg = "图片格式不正确";
                code = 105;
                result.setCode(code);
                result.setMsg(result_msg);
            }
        }
        return result;
    }


}
